﻿using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Reporting.WebForms;
using System.Xml.Serialization;
using System.Xml;

using DQS.Core.Log;
using DQS.Core.RDLC;
using DQS.BLL;

public partial class Operate_ShowData : DQS_Page
{
    private DataSet m_dataSet;
    private MemoryStream m_rdl;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["queryid"] == null)
            {
                Response.Redirect("~/Operate/Columns.aspx");
            }
            LoadData();
        }
    }

    private void LoadData()
    {        
        int queryid = Int32.Parse(Request.QueryString["queryid"].ToString());
        Log.Instance(this).Debug("{QueryID:" + queryid.ToString() + ",Event:Pre Load}");
        m_dataSet = DQ_QUERYManager.GetQueryResult(queryid);
        Log.Instance(this).Debug("{QueryID:" + queryid.ToString() + ",Event:Load Complete}");
        ResultReport.LocalReport.DisplayName = "请输入文件名";
        if (m_rdl != null)
            m_rdl.Dispose();
        m_rdl = GenerateRdl();
        Log.Instance(this).Debug("{QueryID:" + queryid.ToString() + ",Event:Generate Report}");
        Show_Report();      
    }

    private void Show_Report()
    {     
        ResultReport.LocalReport.LoadReportDefinition(m_rdl);
        ResultReport.LocalReport.DataSources.Clear();
        ResultReport.LocalReport.DataSources.Add(new ReportDataSource("MyData", m_dataSet.Tables[0]));
        ResultReport.LocalReport.Refresh();
    }

    private MemoryStream GenerateRdl()
    {
        MemoryStream ms = new MemoryStream();
        RdlGenerator gen = new RdlGenerator();
        gen.SelectedFields = GetAvailableFields();
        gen.WriteXml(ms);
        ms.Position = 0;
        return ms;
    }

    private List<string> GetAvailableFields()
    {
        DataTable dataTable = m_dataSet.Tables[0];
        List<string> availableFields = new List<string>();
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            availableFields.Add(dataTable.Columns[i].ColumnName);
        }
        return availableFields;
    }

    protected void ResultReport_ReportError(object sender, ReportErrorEventArgs e)
    {
        Log.Instance(this).Error(e.Exception.Message);
    }
}
